package cn.south.campus.common.utils;

import org.slf4j.Logger;
import org.slf4j.MDC;
import org.springframework.util.StringUtils;

import java.text.MessageFormat;

/**
 * <p>
 *
 * </p>
 *
 * @author chow
 * @since 2022/5/7 14:36
 */
public class LoggerUtil {
    public static void info(Logger logger, String pattern, Object... obj) {
        logger.info(getFormat(pattern, obj));
    }

    public static void warn(Logger logger, String pattern, Object... obj) {
        logger.warn(getFormat(pattern, obj));
    }

    public static void warn(Logger logger, Exception e, String pattern, Object... obj) {
        logger.warn(getFormat(pattern, obj), e);
    }

    public static void error(Logger logger, String pattern, Object... obj) {
        logger.error(getFormat(pattern, obj));
    }

    public static void error(Logger logger, Exception e, String pattern, Object... obj) {
        logger.error(getFormat(pattern, obj), e);
    }

    private static String getFormat(String pattern, Object[] obj) {
        String traceId = MDC.get("traceId");
        if (traceId == null) {
            return MessageFormat.format(pattern, obj);
        }
        if (!StringUtils.hasLength(pattern)) {
            return "[" + traceId + "]";
        }
        return "[" + traceId + "]" + MessageFormat.format(pattern, obj);
    }
}
